(function ($) {
    if ($.fn.customerDialog) return;
//    if (!$.fn.customerDialog) {
        var panel, header, title, body, buttonPanel, holder, afterShow,
            stack = [],
            status = 'hidden',
            defaults = {
                title: 'Dialog', // default dialog title
                showHeader: true,
                showButtonPanel:true,
                showDefaultCancelButton: false,
                showMask: true,
                modal:true,
                type:'custom'  // default dialog type, it will be one of {message|prompt|error|selection}
                               // current version, only message supported
            }, titleText = {
                message: '提示', prompt: '问题', success: '成功', waring:'警告', error:'错误'
            }, btnClose = {
                label:'确定', callback: cancel
            };

        var allClassNames = (function (a) {
            var s = '';
            for (var key in a) {
                if (key != 'message') {
                if (s.length > 0) s += ' ';
                    s += 'dialog-type-' + key;
                }
            }
            return s;
        } (titleText));

        function createPanel () {
            panel = $('<div/>').appendTo ($(document.body)).attr ('class','dialog-root');
            header = $('<div/>').appendTo (panel).addClass ('ui-state-default dialog-header');
            title = $('<div/>').appendTo (header).addClass ('dialog-title');
            var closeButton = $('<a/>').appendTo (header).addClass ('dialog-close-button action-icon');
            $('<span/>').appendTo (closeButton).addClass ('ui-icon ui-icon-circle-close').on ('click', cancel);
            $('<div/>').appendTo (header).addClass ('clear');

            body = $('<div/>').appendTo (panel).addClass ('dialog-body');
            $('<div/>').appendTo (panel).addClass ('clear');

            buttonPanel = $('<div/>').appendTo (panel).addClass ('dialog-button-panel');
            holder = $('<div/>').css ('display', 'none').appendTo (panel);
        }

        function unloadBody () {
            var e = panel.data ('current');
            if (e) {
                var p = e.data ('parent');
                if (p)
                    e.appendTo ($(p)).hide ();
                else
                    e.remove ();

                if (panel.parent()[0] != document.body) {
                    panel.appendTo ($(document.body));
                }
            }
            stack.length == 0 && panel.removeData ('current');
        }

        function cancel (opt) {
            var self = panel.data ('current'), prev = stack.pop (), settings = self.data ('settings');
            unloadBody ();
            if (prev) {
                openDialog (prev);
                show ();
            } else {
                panel.hide ();
                //modify by 2014-10-20, 增加不关闭遮罩参数;
                if(!!opt
                	&& "notHideMask" in opt	){
                }else{
                    if (typeof opt == 'function') {
                        settings && settings ['showMask'] && mask.hide  (opt);
                    } else {
                        settings && settings ['showMask'] && mask.hide();
                    }
                }
                if ('onclose' in settings) {
                    settings ['onclose'] ();
                }
                delete $.fn.customerDialog.currentDialog;
            }
            status = 'hidden';
        }

        function nothing () {}

        function show () {
            panel.show ();
            var W = $(window).width (), H = $(window).height (), w, h, x, y;
            if ($.support.leadingWhitespace || (dw.Browser.isIe && dw.Browser.version == 8)) {
                w = panel.width ();
                h = panel.height ();
            } else {
                w = body.get (0).scrollWidth;
                h = panel.height ();
                panel.css ({width:w});
            }
            x = (W - w) / 2;
            y = (H - h) / 2;
            panel.css ({left:x, top:y});
            status = 'show';
            
            if(afterShow != undefined){
            	try{
            		afterShow();
            	}catch(e){}
            }
        }

        function buildButtonPanel (settings) {
            if (settings ['buttons']) {
                $(settings ['buttons']).each (function (i, button) {
                    var label = button ['label'] || 'button ' + i;
                    var callback = button ['callback'] || nothing;
                    var btn = $('<a/>').appendTo (buttonPanel).text (label).on ('click', function (event) {
                        callback ($.fn.customerDialog.currentDialog);
                    });

                    if (isPredefineType (settings)) {
                        // btn.button ();
                        if (label == '是') {
                            btn.addClass('dialog-button-save');
                        } else if (label == '否') {
                            btn.addClass('dialog-button-cancel');
                        }
                    } else if ('classes' in button) {
                        btn.addClass (button ['classes']);
                    } else {
                        btn.addClass ('dialog-button-save');
                    }
                });
            }
            if (settings['showDefaultCancelButton']) {
                $('<a/>').appendTo (buttonPanel).addClass('dialog-button-cancel').text ('取消').on ('click', cancel);
            }

            if (isPredefineType (settings)) {
                //buttonPanel.removeClass ('dialog-button-panel').addClass ('internal-dialog-button-panel');
            } else {
                buttonPanel.removeClass ('internal-dialog-button-panel').addClass ('dialog-button-panel');
            }
        }

        function isPredefineType (settings) {
            if (!('type' in settings)) return false;
            var type = settings ['type'];
            return type in titleText;
        }

        function openDialog (sender) {
            var settings = sender.data ('settings'), parent = $(sender.data ('parent'));
            panel.removeClass (allClassNames);
            if (isPredefineType (settings)) {
                var dialogType = settings ['type'];
                panel.addClass ('dialog-type-' + dialogType);
                settings ['title'] = titleText [dialogType];
                settings ['showHeader'] = true;
                settings ['showDefaultCancelButton'] = false;
            }
            title.text (settings ['title']);

            settings ['showHeader'] ? header.show () : header.hide ();
            settings ['showButtonPanel'] ? buttonPanel.show () : buttonPanel.hide ();

            sender.appendTo (body).show ();
            buttonPanel.empty ();
            buildButtonPanel (settings);
            //$('.button').button ();
            panel.data ('current', sender);
            ('move' in settings && settings ['move'] === false) && panel.appendTo (parent);
            $.fn.customerDialog.currentDialog = {close: cancel, sender:sender};
        }

        $.fn.customerDialog = function (options) {
            if (!panel) createPanel ();
            
            var settings = $.extend ({}, defaults, options || {}), self = $(this),
                prevDialog = panel.data ('current');
            prevDialog && function () {
                stack.push (prevDialog);
                prevDialog.appendTo (holder);
            } ();

            self.data ('settings', settings);
            self.data ('parent', this.parent()[0]);

            ('beforeShow' in settings) && settings ['beforeShow'] ();
            
            //2015-03-02 新增对话框显示后调用方法;
            afterShow = settings["afterShow"];
            
            openDialog (self);

            'showMask' in settings && status == 'hidden' ? mask.show ( show ): show ();
            return self;
        };

        $.fn.customerDialog.alert = function (message) {
            $('<span>' + message + '</span>').customerDialog ({type:'message', buttons:[btnClose]});
        };
        $.fn.customerDialog.prompt = function (message, yes, no, opts) {
            var options = $.extend ({}, {type:'prompt', buttons:[{
                label:'是', callback: function (event) { yes (event); cancel ();}
            },{
                label:'否', callback: function (event) { if (no) no (event); cancel ();}
            }]}, opts || {});
            $('<div />').addClass ('inner-dialog-panel').html (message).customerDialog (options);
        };
        $.fn.customerDialog.success = function (message) {
            $('<div>' + message + '</div>').addClass ('inner-dialog-panel').customerDialog ({type:'success', buttons:[btnClose]});
        };
        $.fn.customerDialog.waring = function (message) {
            $('<div>' + message + '</div>').addClass ('inner-dialog-panel').customerDialog ({type:'waring', buttons:[btnClose]});
        };
        $.fn.customerDialog.error = function (message) {
            $('<div>' + message + '</div>').addClass ('inner-dialog-panel').customerDialog ({type:'error', buttons:[btnClose]});
        };
//    }
}) (jQuery);